package com.zsoft.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

/**
 * 日期转换类
 * @author zuoshuaiok@gmail.com
 *
 * 2013-4-22
 */
public class VelocityToolDateUtils {

	public static SimpleDateFormat format = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");

	public static SimpleDateFormat formatMinute = new SimpleDateFormat("HH:mm");

	public static SimpleDateFormat formathour = new SimpleDateFormat(
			"yyyy-MM-dd HH");

	public static SimpleDateFormat formatperiod = new SimpleDateFormat(
			"yyyy-MM-dd");

	private static SimpleDateFormat formattypeb = new SimpleDateFormat(
			"yyyyMMdd");

	private static SimpleDateFormat formatStr = new SimpleDateFormat("MM月dd");

	private static SimpleDateFormat formats = new SimpleDateFormat("MM/dd");

	/**
	 * 
	 * @param day
	 * @return
	 */
	public static String getDay(int day) {

		Date date = DateUtils.truncate(DateUtils.addDays(new Date(), day),
				Calendar.DATE);
		return formatperiod.format(date);
	}

	public static String getTime(int time) {
		Date date = new Date(Long.valueOf(time + "000"));
		return Globals.FORMAT_TYPE_E.format(date);
	}

	public static String getDetailTime(int seconds) {
		int days = seconds / (3600 * 24);
		int mod = seconds % (3600 * 24);
		int hour = mod / 3600;
		mod = mod % 3600;
		int min = mod / 60;
		int second = mod % 60;
		if (days == 0) {
			if (hour == 0) {
				if (min == 0) {
					return second + "秒";
				} else {
					return min + "分" + second + "秒";
				}
			} else {
				return hour + "时" + min + "分" + second + "秒";
			}
		} else {
			return days + "天" + hour + "时" + min + "分" + second + "秒";
		}
	}

	public String getCurrentTime(int time) {
		Date date = new Date();
		int currentTime = (int) (date.getTime() / 1000);
		int minusTime = currentTime - time;
		String times = getDetailTime(minusTime);
		return times;
	}

	public String getTotalCurrentTime(int startTime, int seconds) {
		Date date = new Date();
		int currentTime = (int) (date.getTime() / 1000);
		int minusTime = currentTime - startTime;
		minusTime = minusTime + seconds;
		String times = getDetailTime(minusTime);
		return times;
	}

	/**
	 * 
	 * @param day
	 * @return
	 */
	public static String getDayFromAt(int day) {

		Date date = DateUtils.truncate(DateUtils.addDays(new Date(), day),
				Calendar.DATE);
		return formats.format(date);
	}

	public static String getHour(int hour) {

		Date date = DateUtils.truncate(DateUtils.addHours(new Date(), hour),
				Calendar.HOUR);
		return formathour.format(date);
	}

	public static String getMinute(int mm) {

		Date date = DateUtils.truncate(DateUtils.addMinutes(new Date(), mm),
				Calendar.MINUTE);
		return format.format(date);
	}

	/**
	 * 上个月的今天
	 * 
	 * @return
	 */

	public String getLastMonthToday() {
		Date date = DateUtils.truncate(DateUtils.addMonths(new Date(), -1),
				Calendar.DATE);

		return formatperiod.format(date);
	}

	/**
	 * 比较两个日期 之间的天数
	 * 
	 * @param from
	 *            4
	 * @param to
	 *            5
	 * @return
	 */
	public static int dayNum(Date from, Date to) {

		Calendar calendar = Calendar.getInstance();

		calendar.setTime(to);

		int day1 = calendar.get(Calendar.DAY_OF_YEAR);

		calendar.setTime(from);

		int day2 = calendar.get(Calendar.DAY_OF_YEAR);

		return day1 - day2;

	}

	/**
	 * 当前时间向后退一个月 之间的
	 * 
	 * 返回 0-------------05月13 -1-------------05月12 -2-------------05月11
	 * -3-------------05月10
	 * 
	 * @return
	 */

	public static LinkedHashMap<String, String> getMonthdayList() {

		LinkedHashMap<String, String> formatDate = new LinkedHashMap<String, String>();

		Date todaydate = new Date();

		Date lastMonthdate = DateUtils.addMonths(todaydate, -1);
		int days = dayNum(lastMonthdate, todaydate);

		formatDate.put(0 + "", formatStr.format(todaydate));

		for (int j = 1; j < days + 1; j++) {
			formatDate.put(-j + "",
					formatStr.format(DateUtils.addDays(todaydate, -j)));
		}

		return formatDate;
	}

	/**
	 * 从给定条件的前一天往前推指定天的一个范围
	 * 
	 * @param d
	 *            从某一天开始
	 * @param days
	 *            要获取的天数
	 * @return
	 */
	public static String getLatestThirtyDays(Date d, int days) {

		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DAY_OF_MONTH, -1);
		String end = formatperiod.format(c.getTime());
		c.add(Calendar.DAY_OF_MONTH, -days);
		String start = formatperiod.format(c.getTime());

		return start + "," + end;
	}

	/**
	 * 获得两个时间段的拼串
	 * 
	 * @param d
	 * @param days
	 * @return
	 */
	public static String getDateRange(Date d, int days) {

		Calendar c = Calendar.getInstance();
		c.setTime(d);

		String end = formatperiod.format(c.getTime());
		c.add(Calendar.DAY_OF_MONTH, -days);
		String start = formatperiod.format(c.getTime());

		return start + "," + end;
	}

	/**
	 * 获取当前月的第一天和最后一天|_z
	 * 
	 * @param formatType
	 *            返回的格式化日期类型 1.yyyyMMdd 2.yyyy-MM-dd 默认返回2
	 * @return
	 */
	public static String getFirstandLastofcurrentMonth(String formatType) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.set(Calendar.DAY_OF_MONTH, 1);
		Date stat = c.getTime();

		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DAY_OF_MONTH, -1);
		Date end = c.getTime();

		if (null != formatType && formatType.equals(Globals.DATE_FORMAT_A)) {
			return formattypeb.format(stat) + "," + formattypeb.format(end);
		} else {
			return formatperiod.format(stat) + "," + formatperiod.format(end);
		}
	}

	/**
	 * 1.获取从某一天开始向后连续的多少天(5号,3天）会返回 (3,4,5) 2.获取两个时间段之间的拼串 | _zuos
	 * 
	 * @param start
	 *            开始的日期 要求类型(yyyy-MM-dd{默认})
	 * @param end
	 *            结束的日期(要求类型(yyyy-MM-dd{默认})
	 * @param days
	 *            要的天数
	 * @param formatType
	 *            要求返回的格式化类型(default:yyyy-MM-dd)
	 * @param dateType
	 *            功能类型 （默认功能1{功能1 @param start 字段可以省略为null}，为2时表示选择功能2)
	 * @return 形如 2012-3-4,2012-3-5,....连续日期拼串
	 * 
	 */
	public static String getSpecifiedContinusDays(String start, String end,
			int days, String formatType, String dateType) {
		StringBuffer retStr = new StringBuffer();
		// 最多执行40次 强制推出
		int k = 40;
		// 返回指定时间段拼串
		Calendar c = Calendar.getInstance();
		if (dateType.equals(Globals.CONDITION_B)) {
			if (StringUtils.isBlank(start) || StringUtils.isBlank(end))
				return null;
			Date m = null;
			try {
				m = formatperiod.parse(start);
			} catch (ParseException e) {
				return null;
			}
			try {
				do {
					if (k < 1)
						break;

					c.setTime(m);
					// 日期加1

					if (formatType != null
							&& formatType.equals(Globals.DATE_FORMAT_B)) {
						retStr.append(formattypeb.format(m) + ",");
					} else {
						retStr.append(formatperiod.format(m) + ",");
					}
					c.add(Calendar.DAY_OF_MONTH, 1);
					m = c.getTime();
					k--;
				} while (formatperiod.parse(end).after(m)
						|| formatperiod.parse(end).equals(m));
			} catch (ParseException e) {
				return null;
			}

		} else {
			try {
				Date m = formatperiod.parse(end);
				c.setTime(m);
				c.add(Calendar.DAY_OF_MONTH, -days);
				Date n = c.getTime();

				for (Date d = n; d.before(m);) {
					if (k < 1)
						break;
					c.setTime(d);
					d = c.getTime();
					c.add(Calendar.DAY_OF_MONTH, 1);
					d = c.getTime();
					if (formatType != null
							&& formatType.equals(Globals.DATE_FORMAT_B)) {
						retStr.append(formattypeb.format(d) + ",");
					} else {
						retStr.append(formatperiod.format(d) + ",");
					}
					k--;
				}
			} catch (ParseException e) {
				return null;
			}
		}
		return retStr.toString();
	}

	public static void main(String[] args) {
		// System.out.println(getMonthdayList());
		// System.out.println(getSpecifiedContinusDays("2012-05-13",3).split(",").length);
		// System.out.println(getSpecifiedContinusDays("2012-05-05", 10));
		// getSpecifiedContinusDays("2012-05-01", "2012-05-22", 0,
		// Globals.DATE_FORMAT_A, Globals.CONDITION_B);
		// String s = getSpecifiedContinusDays("2012-05-01", "2012-05-03", 30,
		// Globals.DATE_FORMAT_A, Globals.CONDITION_B);
		// String s=getFirstandLastofcurrentMonth(null);
		// System.out.println(s);

		// String ret = getDateRange(new Date(), -1);
		// System.out.println(ret);

	}

	// 最近30天
	public static List<Map.Entry<String, String>> getThirtydayList() {
		LinkedHashMap<String, String> formatDate = new LinkedHashMap<String, String>();
		Date todaydate = new Date();
		Date lastMonthdate = DateUtils.addMonths(todaydate, -1);
		int days = dayNum(lastMonthdate, todaydate);
		formatDate.put(0 + "", formats.format(todaydate));
		for (int j = 1; j < days - 1; j++) {
			formatDate.put(-j + "",
					formats.format(DateUtils.addDays(todaydate, -j)));
		}
		// 倒序
		List<Map.Entry<String, String>> map = null;
		map = new ArrayList<Map.Entry<String, String>>(formatDate.entrySet());
		Collections.sort(map, new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Map.Entry<String, String> o1,
					Map.Entry<String, String> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		return map;
	}

	public static List<Map.Entry<String, String>> getThirtyday() {
		LinkedHashMap<String, String> formatDate = new LinkedHashMap<String, String>();
		Date todaydate = new Date();
		Date lastMonthdate = DateUtils.addMonths(todaydate, -1);
		int days = dayNum(lastMonthdate, todaydate);
		formatDate.put(0 + "", formatperiod.format(todaydate));
		for (int j = 1; j < days - 1; j++) {
			formatDate.put(-j + "",
					formatperiod.format(DateUtils.addDays(todaydate, -j)));
		}
		List<Map.Entry<String, String>> map = null;
		map = new ArrayList<Map.Entry<String, String>>(formatDate.entrySet());
		Collections.sort(map, new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Map.Entry<String, String> o1,
					Map.Entry<String, String> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		return map;
	}

	public static String fromatDay(Date date) throws ParseException {
		String day = null;
		SimpleDateFormat type2 = new SimpleDateFormat("E");
		String date1 = type2.format(date);
		if (date1.equals("星期六") || date1.equals("星期日")) {
			day = Globals.FORMAT_TYPE_A.format(date) + "<font color='red'> "
					+ date1 + " </font>";
		} else {
			day = Globals.FORMAT_TYPE_A.format(date);
		}
		return day;
	}

	/**
	 * 获取当前月的第一天
	 * 
	 * @param formatType
	 *            返回的格式化日期类型 yyyy-MM-dd
	 * @return
	 */
	public static String getMonthFirstDay() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
		Date end = c.getTime();
		return formatperiod.format(end);
	}
}
